<?php

namespace Sdk\lib;

use Run;

class Config {

	const ConfigFile = './conf/config.ini';

	public static function GetRoot($key = null) {
		$path = ROOT_PATH . '/';
		return self::GetConf($path, $key);
	}

	public static function GetApp($key = null) {
		$path = Run::getInstance()->_appPath;
		return self::GetConf($path, $key);
	}

	public static function SetRoot($data) {
		$path = ROOT_PATH . '/';
		return self::SetConf($path, $data);
	}

	public static function SetApp($data) {
		$path = Run::getInstance()->_appPath;
		return self::SetConf($path, $data);
	}

	public static function SetConf($path, $data) {
		$lf = "\n";
		$content = "";
		foreach ($data as $key => $elem) {
			$content .= '[' . $key . ']' . $lf;
			foreach ($elem as $key2 => $elem2) {
				if (is_array($elem2)) {
					for ($i = 0; $i < count($elem2); $i++) {
						$content .= $key2 . '[] = "' . $elem2[$i] . '"' . $lf;
					}
				} else if ($elem2 == '') {
					$content .= $key2 . ' = ' . $lf;
				} else {
					$content .= $key2 . ' = "' . $elem2 . '"' . $lf;
				}
			}
		}
		$configFile = $path . self::ConfigFile;
		if (!$handle = fopen($configFile, 'w')) {
			return false;
		}
		$success = fwrite($handle, $content);
		fclose($handle);
		return $success;
	}

	/**
	 * @param $path
	 * @param $key
	 * @return mixed|null
	 */
	public static function GetConf($path, $key = null) {
		$configFile = $path . self::ConfigFile;
		if (!file_exists($configFile)) {
			return null;
		}
		$data = parse_ini_file($configFile, true);
		if (!empty($key)) {
			return isset($data[$key]) ? $data[$key] : null;
		} else {
			return $data;
		}
	}

}